<template>
  <view class="cart">
    <view class="cart_address">
      <view v-if="address" class="address_info">
        <view class="address_name_wrap">
          <view>{{ address.userName }}</view>
          <view>{{ address.detail }}</view>
        </view>
        <view class="address_phone">{{ address.telNumber }}</view>
      </view>
      <view class="cart_btn" v-else>
        <van-button color="#d81e06" type="primary" @click="getAddress"
          >收货地址</van-button
        >
      </view>
      <!-- 购物车内容 -->
      <view class="cart_main">
        <view class="cart_title">购物车</view>
        <view class="cart_content">
          <view v-if="cartList.length">
            <van-swipe-cell
              async-close
              @close="onCartClose"
              :right-width="65"
              v-for="(item, index) in cartList"
              :key="index"
            >
              <view class="cart_item">
                <!-- xxxx -->
                <view class="ckd_wrap"
                  ><van-checkbox
                    shape="square"
                    checked-color="#ff2d4a"
                    :value="item.checked"
                    @change="onChange(index)"
                  ></van-checkbox
                ></view>
                <view class="item_goods">
                  <van-card
                    :price="item.goods_price"
                    :title="item.goods_name"
                    :thumb="
                      item.goods_small_logo ||
                      'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3030023840,1652137957&fm=26&gp=0.jpg'
                    "
                    custom-class="custom_class"
                  >
                    <view slot="footer">
                      <van-stepper
                        :value="item.count"
                        @change="onCountChange(index, $event)"
                        async-change
                        min="0"
                      />
                    </view>
                  </van-card>
                </view>
                <!-- xxxx -->
              </view>

              <view slot="right" class="cart_del">删除</view>
            </van-swipe-cell>
          </view>
          <view v-else
            ><image
              src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602785522516&di=5668b0d5d336c18e1dc0e3d4425caa4f&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20171105%2F1d5242d91765473a88462a2e3e7133b6.gif"
            ></image
          ></view>
        </view>
      </view>
    </view>
    <van-submit-bar custom-class="custom_class_btn" :price="countInfo.allPrice" @submit="onClickButton" :button-text="`结算 (${countInfo.cateNum})`" :tip="true">
      <van-checkbox :value="countInfo.allChk" @change="onAllChange" shape="square" checked-color="#ff2d4a">全选</van-checkbox>
    </van-submit-bar>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 地址对象
      address: null,
      // 购物车数组
      cartList: [],
    };
  },
  // 监听
  watch: {
    // cartList(){} 浅监控
    cartList: {
      // deep 深层监控
      deep: true,
      // handler 数据改变之后的模样
      handler(list) {
        uni.setStorageSync("cartList", list);
      },
    },
  },
  computed:{
    countInfo(){
      // 1.是否全选 every
      let allChk = this.cartList.length !==0 && this.cartList.every((goods)=>goods.checked) 
      // 2.计算总价格
      let allPrice = 0;
      this.cartList.forEach((goods)=>{
        // 已经勾选的商品
        if(goods.checked){
          allPrice += goods.count * goods.goods_price;
        }
      });
      // 准备要结算的商品种类
      let cateNum = this.cartList.filter((goods)=>goods.checked).length
      return{
        // 是否全选
        allChk,
        // 总价格
        allPrice:allPrice*100,
        // 准备要结算的商品种类 cateNum
        cateNum
      }
    }
  },
  onShow() {
    // 获取本地存储中的购物车的数据 数组
    this.cartList = uni.getStorageSync("cartList") || [];
  },
  methods: {
    // 地址事件
    async getAddress() {
      const res = await uni.chooseAddress();
      console.log(res);
      this.address = res[1];
      this.address.detail =
        this.address.provinceName +
        this.address.cityName +
        this.address.countyName +
        this.address.detailInfo;
    },
    // 商品的复选框选中
    onChange(index) {
      this.cartList[index].checked = !this.cartList[index].checked;
    },
    // 数量改变事件
    onCountChange(index, event) {
      if (event.detail === 0) {
        this.deleteByIndex(index);
      } else {
        this.cartList[index].count = event.detail;
      }
    },
    // 点击删除事件
    async onCartClose(event) {
      const { instance } = event.detail;
      await this.deleteByIndex(0);
      instance.close();
    },
    // 封装根据索引来弹出创建删除数据
    // deleteByIndex 返回一个 promise
    async deleteByIndex(index) {
      const result = await uni.showModal({
        title: "提示",
        content: "您确定要删除吗",
      });
      if (result[1].confirm) {
        // console.log("执行删除");
        this.cartList.splice(index, 1);
        wx.showToast({
          title: "删除成功！",
        });
      }
    },
    // 复选框全选事件
    onAllChange(){
      // 1.获取计算属性中 全选状态 = true
      // 2.对购物车数组做遍历即可
      // 3.获取到每一个商品对象 goods.checked=!全选状态
      const allChk = this.countInfo.allChk;
      this.cartList.forEach((goods)=>{
        goods.checked = !allChk;
        // ! this.countInfo.allChk; 如果一旦修改数组,那么allchk不稳定
      })
    },
    // 结算事件
    onClickButton(){
      // 判断是否合法  有无地址，数量不为零
      if(!this.address || this.countInfo.cateNum ===0){
        uni.showToast({title:"请检查收货地址或购买商品数量",icon:"none"});
        return;
      }else{
        // 传递参数: 1url 2本地存储 3全局应用对象getApp()
        const app = getApp();
        app.globalData.address = this.address;
        uni.navigateTo({url:"/pages/pay/pay"});
      }
    }
  },
};
</script>

<style lang="less">

.cart_address {
  .address_info {
    display: flex;
    justify-content: space-between;
    padding: 20rpx;
    border-bottom: 1rpx solid#e94350;
  }
  .cart_btn {
    display: flex;
    justify-content: center;
    padding-top: 20rpx;
  }
}
.cart_main {
  .cart_title {
    padding: 20rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #eb4450;
    border-top: 1rpx solid #eb4450;
    border-bottom: 1rpx solid #eb4450;
  }
}
.cart_content {
  .cart_item {
    border-bottom: 2rpx solid #ccc;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
  }
  .item_goods{
    flex: 1;
  }
  .custom_class {
    background-color: #fff !important;
  }
  .cart_del {
    background-color: #eb4450;
    color: #fff;
    width: 65px;
    height: 100%;
    font-size: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.custom_class_btn{
    border-top: 2rpx solid #ccc!important;
}
</style>